package com.top.art.controller;

import com.top.art.annotation.PermissionLimit;
import com.top.art.exception.ArtException;
import com.top.art.service.IPaperService;
import com.top.art.utils.AliyunOssUtil;
import com.top.art.vo.PaperFileVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ContentDisposition;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

/**
 * @description:
 * @author: huangyixin
 * @create: 2020/10/11 09:46
 **/
@Slf4j
@Controller
@RequestMapping("/paper")
public class PaperController {

    @Autowired
    private AliyunOssUtil aliyunOssUtil;

    @Autowired
    private IPaperService iPaperService;

    @GetMapping(value = "/downloadFile")
    @PermissionLimit(limit = false)
    public ResponseEntity<byte[]> downloadFile(String objectName) throws IOException {
        PaperFileVO paper = aliyunOssUtil.downloadFile(objectName);
        HttpHeaders headers = new HttpHeaders();
        ContentDisposition contentDisposition = ContentDisposition.builder("attachment")
                .filename(paper.getFileName()).build();
        headers.setContentDisposition(contentDisposition);
        headers.setContentType(MediaType.valueOf(paper.getContentType()));

        return ResponseEntity.ok().headers(headers).body(FileCopyUtils.copyToByteArray(paper.getFile()));
    }

    @GetMapping(value = "/downloadPaper")
    @PermissionLimit(limit = false)
    public ResponseEntity<byte[]> downloadPaper(String studioCode) throws IOException {
        if (StringUtils.isBlank(studioCode)) {
            throw ArtException.buildException("缺少画室编码");
        }
        File file = iPaperService.downloadPaper(studioCode);
        HttpHeaders headers = new HttpHeaders();
        String contentDisposition = "attachment;filename="
                + new String(file.getName().getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1)
                + ";filename*=utf-8''" + URLEncoder.encode(file.getName(), "UTF-8");
        headers.set("Content-Disposition", contentDisposition);
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        ResponseEntity<byte[]> responseEntity = ResponseEntity.ok().headers(headers).body(FileCopyUtils.copyToByteArray(file));
        FileUtils.deleteQuietly(file);
        return responseEntity;
    }
}
